//
//  WmcCancellationPolicyWebVC.swift
//  YPWatermarkCamera
//
//  Created by 马涛 on 2022/6/20.
//

import Toast_Swift
import UIKit
import WebKit

// MARK: - 扩展WmcCancellationPolicyWebVC + WmcNavigatorProtocol

extension WmcCancellationPolicyWebVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.cancellationPolicy]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vc = UIViewController()
        if let param = parms.context as? [String : Any],let url = param["url"] as? String  {
            let vm = WmcCancellationPolicyWebVM()
            vm.url = url
            vc = WmcCancellationPolicyWebVC(vm)
        }
        return vc
    }
}

// MARK: - 扩展WmcCancellationPolicyWebVC + WmcVMProtocol

extension WmcCancellationPolicyWebVC: WmcVMProtocol {
    typealias VMType = WmcCancellationPolicyWebVM
}

// MARK: - [WmcCancellationPolicyWebVC]

class WmcCancellationPolicyWebVC: WmcBaseVC {
    // Lifecycle

    // MARK: 系统方法

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "注销协议"
    }
        
    override func makeUI() {
        makeNavView(showShadow: false)
        addSubview(webView)
        webView.snp.makeConstraints { make in
            make.top.equalTo(self.navView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        if let uStr = urlStr, let url = URL(string: uStr) {
            WmcHudManager.loading()
            webView.load(URLRequest(url: url))
        }
    }

    // Internal

    // MARK: UI属性

    lazy var config: WKWebViewConfiguration = {
        let config = WKWebViewConfiguration()
        let userContentController = WKUserContentController()
        config.userContentController = userContentController

        let preferences = WKPreferences()
        preferences.minimumFontSize = 12
        preferences.javaScriptCanOpenWindowsAutomatically = true
        config.preferences = preferences

        return config
    }()

    lazy var webView: WKWebView = {
        let view = WKWebView(frame: .zero, configuration: config)
        view.uiDelegate = self
        view.navigationDelegate = self
        view.scrollView.bounces = true
        view.scrollView.showsVerticalScrollIndicator = false
        return view
    }()

    // MARK: 非UI属性

    var urlStr: String? {
        return self.viewModel.url
    }
}

// MARK: - WKNavigationDelegate, WKUIDelegate

extension WmcCancellationPolicyWebVC: WKNavigationDelegate, WKUIDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        WmcHudManager.dismiss()
    }

    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        self.view.makeToast(error.localizedDescription)
    }
}
